package com.dm.cloud.configurations;

import com.dm.cloud.common.CloudConstant;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 发送FeignClient设置Header信息.
 * http://www.itmuch.com/spring-cloud-sum/hystrix-threadlocal/
 * Hystrix传播ThreadLocal对象
 */
@Component
public class TokenFeignClientInterceptor implements RequestInterceptor {
  /**
   * token放在请求头.
   *
   * @param requestTemplate 请求参数
   */
  @Override
  public void apply(RequestTemplate requestTemplate) {
    RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
    if (requestAttributes != null) {
      HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
      requestTemplate.header("Authorization", request.getHeader("Authorization"));
      byte[] token = Base64Utils.encode((CloudConstant.GATEWAY_TOKEN_VALUE).getBytes());
      String[] headerValues = {new String(token)};
      requestTemplate.header(CloudConstant.GATEWAY_TOKEN_HEADER, headerValues);
    }
  }
}